import React, { memo, useEffect, useState, useMemo } from 'react';
import { 
  Card, 
  Button, 
  Row, 
  Col, 
  Space, 
  Typography, 
  Divider,
  Modal,
  message,
  Spin,
  Tabs,
  Badge
} from 'antd';
import type { TabsProps } from 'antd';
import { 
  PlusOutlined, 
  UserOutlined, 
  CalendarOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { 
  StudentCard, 
  StudentForm, 
  StudentList, 
  StudentSearch 
} from '@/components/business/student';
import { DailyScheduleView } from '@/components/business/schedule';
import { useStudentManagement, useStudentSelection } from '@/store/student';
import { useScheduleManagement } from '@/store/schedule';
import { useCourseManagement } from '@/store/course';
import { getCurrentDate } from '@/utils/date';
import type { IStudent } from '@/types/student';
import type { StudentStatusEnum } from '@/types/student';
import styles from './StudentPage.module.css';

const { Title, Text } = Typography;
const { confirm } = Modal;

/**
 * 学生管理页面组件
 * @description 提供学生的增删改查功能和课表查看功能
 */
const StudentPage: React.FC = memo(() => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  
  // 本地状态
  const [showForm, setShowForm] = useState(false);
  const [formMode, setFormMode] = useState<'create' | 'edit'>('create');
  const [currentStudent, setCurrentStudent] = useState<IStudent | null>(null);
  const [showScheduleModal, setShowScheduleModal] = useState(false);
  const [scheduleStudent, setScheduleStudent] = useState<IStudent | null>(null);
  const [activeTab, setActiveTab] = useState('list');

  // 状态管理
  const {
    students,
    isLoading,
    error,
    fetchStudents,
    addStudent,
    updateStudent,
    deleteStudent
  } = useStudentManagement();

  const {
    selectedStudentIds,
    selectedStudents,
    toggleSelection,
    clearSelection
  } = useStudentSelection();

  const {
    instances,
    refresh: refreshSchedule
  } = useScheduleManagement();
  
  const {
    courses
  } = useCourseManagement();

  // 初始化数据
  useEffect(() => {
    const initializeData = async () => {
      try {
        await Promise.all([
          fetchStudents(),
          refreshSchedule()
        ]);
      } catch (error) {
        console.error('初始化学生页面数据失败:', error);
        message.error('加载数据失败，请刷新页面重试');
      }
    };

    initializeData();
  }, []); // 移除函数依赖，避免无限循环

  // 处理URL参数
  useEffect(() => {
    const action = searchParams.get('action');
    const studentId = searchParams.get('studentId');

    if (action === 'create') {
      handleCreateStudent();
    } else if (action === 'edit' && studentId) {
      const student = students.find(s => s.id === studentId);
      if (student) {
        handleEditStudent(student);
      }
    }
  }, [searchParams, students]);

  // 筛选后的学生列表
  const filteredStudents = useMemo(() => {
    return students.filter(student => student.status !== 4); // 排除已删除的学生
  }, [students]);

  // 按状态分组的学生统计
  const studentStats = useMemo(() => {
    const stats = {
      total: 0,
      active: 0,
      inactive: 0,
      graduated: 0
    };

    filteredStudents.forEach(student => {
      stats.total++;
      switch (student.status) {
        case 1: // ACTIVE
          stats.active++;
          break;
        case 2: // INACTIVE
          stats.inactive++;
          break;
        case 3: // GRADUATED
          stats.graduated++;
          break;
      }
    });

    return stats;
  }, [filteredStudents]);

  // 获取学生的课程实例
  const getStudentSchedules = (studentId: string) => {
    return instances.filter(instance => instance.studentId === studentId);
  };

  // 标签页配置
  const tabItems: TabsProps['items'] = useMemo(() => [
    {
      key: 'list',
      label: (
        <span>
          <UserOutlined />
          学生列表
          <Badge count={filteredStudents.length} showZero style={{ marginLeft: 8 }} />
        </span>
      ),
      children: (
        <Card className={styles.listCard}>
          {/* 搜索区域 */}
          <div className={styles.searchSection}>
            <StudentSearch
              onSearch={(keyword) => {
                // 搜索功能由StudentList组件内部处理
              }}
              placeholder="搜索学生姓名、学号、班级..."
            />
          </div>

          {/* 学生列表 */}
          <StudentList
            students={filteredStudents}
            loading={isLoading}
            selectedStudentIds={selectedStudentIds}
            onSelect={(studentIds: string[]) => {
              studentIds.forEach(id => toggleSelection(id));
            }}
            onEdit={(student) => {
              handleEditStudent(student);
            }}
            onDelete={(id) => {
              const student = students.find(s => s.id === id);
              if (student) handleDeleteStudent(student);
            }}
            onViewSchedule={(id) => {
              const student = students.find(s => s.id === id);
              if (student) handleViewSchedule(student);
            }}
            className={styles.studentList}
          />
        </Card>
      )
    },
    {
      key: 'statistics',
      label: (
        <span>
          <CalendarOutlined />
          课程统计
        </span>
      ),
      children: (
        <Card className={styles.statisticsCard}>
          <Row gutter={[16, 16]}>
            {filteredStudents.map(student => {
              const schedules = getStudentSchedules(student.id);
              return (
                <Col xs={24} sm={12} lg={8} xl={6} key={student.id}>
                  <StudentCard
                    student={student}
                    onEdit={() => handleEditStudent(student)}
                    onDelete={() => handleDeleteStudent(student)}
                    onViewSchedule={() => handleViewSchedule(student)}
                  />
                </Col>
              );
            })}
          </Row>
        </Card>
      )
    }
  ], [filteredStudents, isLoading, selectedStudentIds, students, instances, courses]);

  // 创建学生
  const handleCreateStudent = () => {
    setCurrentStudent(null);
    setFormMode('create');
    setShowForm(true);
    // 清除URL参数
    setSearchParams({});
  };

  // 编辑学生
  const handleEditStudent = (student: IStudent) => {
    setCurrentStudent(student);
    setFormMode('edit');
    setShowForm(true);
  };

  // 删除学生
  const handleDeleteStudent = (student: IStudent) => {
    confirm({
      title: '确认删除学生',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>确定要删除学生 <strong>{student.name}</strong> 吗？</p>
          <p style={{ color: '#ff4d4f', fontSize: '12px' }}>
            删除后该学生的所有课程安排也将被删除，此操作不可恢复。
          </p>
        </div>
      ),
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteStudent(student.id);
          message.success('学生删除成功');
          clearSelection();
        } catch (error) {
          console.error('删除学生失败:', error);
          message.error('删除学生失败，请重试');
        }
      }
    });
  };

  // 查看学生课表
  const handleViewSchedule = (student: IStudent) => {
    setScheduleStudent(student);
    setShowScheduleModal(true);
  };

  // 表单提交
  const handleFormSubmit = async (formData: any) => {
    try {
      if (formMode === 'create') {
        await addStudent(formData);
        message.success('学生添加成功');
      } else {
        await updateStudent(currentStudent!.id, formData);
        message.success('学生信息更新成功');
      }
      setShowForm(false);
      setCurrentStudent(null);
    } catch (error) {
      console.error('保存学生信息失败:', error);
      message.error(formMode === 'create' ? '添加学生失败' : '更新学生信息失败');
    }
  };

  // 表单取消
  const handleFormCancel = () => {
    setShowForm(false);
    setCurrentStudent(null);
    // 清除URL参数
    setSearchParams({});
  };

  // 批量操作
  const handleBatchDelete = () => {
    if (selectedStudentIds.length === 0) {
      message.warning('请先选择要删除的学生');
      return;
    }

    confirm({
      title: '批量删除学生',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除选中的 ${selectedStudentIds.length} 个学生吗？此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await Promise.all(selectedStudentIds.map(id => deleteStudent(id)));
          message.success(`成功删除 ${selectedStudentIds.length} 个学生`);
          clearSelection();
        } catch (error) {
          console.error('批量删除学生失败:', error);
          message.error('批量删除失败，请重试');
        }
      }
    });
  };

  return (
    <div className={styles.studentPage}>
      {/* 页面头部 */}
      <div className={styles.pageHeader}>
        <div className={styles.headerContent}>
          <div className={styles.titleSection}>
            <Title level={2} className={styles.pageTitle}>
              <UserOutlined /> 学生管理
            </Title>
            <Text type="secondary">
              管理学生信息，查看学生课程安排
            </Text>
          </div>
          <div className={styles.actionSection}>
            <Space>
              {selectedStudentIds.length > 0 && (
                <>
                  <Button 
                    danger 
                    onClick={handleBatchDelete}
                    icon={<DeleteOutlined />}
                  >
                    批量删除 ({selectedStudentIds.length})
                  </Button>
                  <Button onClick={clearSelection}>
                    取消选择
                  </Button>
                </>
              )}
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleCreateStudent}
              >
                添加学生
              </Button>
            </Space>
          </div>
        </div>

        {/* 统计信息 */}
        <Row gutter={16} className={styles.statsRow}>
          <Col span={6}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber}>{studentStats.total}</div>
                <div className={styles.statLabel}>总学生数</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#52c41a' }}>
                  {studentStats.active}
                </div>
                <div className={styles.statLabel}>在读学生</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#faad14' }}>
                  {studentStats.inactive}
                </div>
                <div className={styles.statLabel}>休学学生</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#1890ff' }}>
                  {studentStats.graduated}
                </div>
                <div className={styles.statLabel}>毕业学生</div>
              </div>
            </Card>
          </Col>
        </Row>
      </div>

      <Divider />

      {/* 主要内容 */}
      <div className={styles.pageContent}>
        <Spin spinning={isLoading}>
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            className={styles.contentTabs}
            items={tabItems}
          />
        </Spin>
      </div>

      {/* 学生表单模态框 */}
      <Modal
        title={formMode === 'create' ? '添加学生' : '编辑学生'}
        open={showForm}
        onCancel={handleFormCancel}
        footer={null}
        width={600}
        destroyOnHidden
      >
        <StudentForm
          student={currentStudent || undefined}
          visible={showForm}
          mode={formMode}
          onSubmit={handleFormSubmit}
          onCancel={handleFormCancel}
        />
      </Modal>

      {/* 学生课表查看模态框 */}
      <Modal
        title={
          <span>
            <CalendarOutlined /> {scheduleStudent?.name} 的课程表
          </span>
        }
        open={showScheduleModal}
        onCancel={() => setShowScheduleModal(false)}
        footer={[
          <Button key="close" onClick={() => setShowScheduleModal(false)}>
            关闭
          </Button>,
          <Button 
            key="manage" 
            type="primary"
            onClick={() => {
              setShowScheduleModal(false);
              navigate(`/schedule?student=${scheduleStudent?.id}`);
            }}
          >
            管理课程表
          </Button>
        ]}
        width={800}
        destroyOnHidden
      >
        {scheduleStudent && (
          <DailyScheduleView
            date={getCurrentDate()}
            scheduleInstances={instances.filter(instance => instance.studentId === scheduleStudent.id)}
            students={[scheduleStudent]}
            courses={courses}
            viewMode="single"
            selectedStudents={[]}
            onInstanceClick={() => {}}
            onDateChange={() => {}}
            className={styles.scheduleView}
          />
        )}
      </Modal>
    </div>
  );
});

StudentPage.displayName = 'StudentPage';

export default StudentPage;